package com.efounder.widget;

/**
 * lch
 * 7-15
 * webview
 */
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.efounder.constant.Constant;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.MyStaticWebView;
import com.efounder.util.WebViewUtil;

public class ESPWebView extends WebView {
	JsToAndroidInterface jsToAndroidInterface;
	LoadInterface loadInterface;
	ProgressDialog progressBar;
	Context espContext;
	
    boolean isinitover = false;

	
	public  boolean isIsinitover() {
		return isinitover;
	}

	public  void setIsinitover(boolean isinitover1) {
		isinitover = isinitover1;
	}
	
	
	private JsToandroidCallBack jsToandroidCallBack;

	public JsToandroidCallBack getJsToandroidCallBack() {
		return jsToandroidCallBack;
	}

	public void setJsToandroidCallBack(JsToandroidCallBack jsToandroidCallBack) {
		this.jsToandroidCallBack = jsToandroidCallBack;
	}

	public void setEspContext(Context espContext) {
		this.espContext = espContext;
	}

	String canScrollscaleArray;

	@SuppressLint("NewApi")
	public ESPWebView(Context context) {
		super(context);
		espContext = context;
		initView();
	}
	@SuppressLint("NewApi")
	public ESPWebView(Context context, AttributeSet attrs) {
		super(context,null);
		espContext = context;
		initView();
	}
	private void initView(){
		this.getSettings().setJavaScriptEnabled(true);
		// 添加javascriptinterface，这个方法重要，this，和后面的string为js中调用android程序提供标志。
		this.addJavascriptInterface(this, "pansoft");
		// this.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

		this.getSettings().setSupportZoom(true);
		this.getSettings().setBuiltInZoomControls(true);
		getSettings().setDisplayZoomControls(false);//设定缩放控件隐藏

		//1 this.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		//1 this.getSettings().setLoadWithOverviewMode(true);

		this.getSettings().setUseWideViewPort(true);
		//1 this.getSettings().setLoadWithOverviewMode(true);

		this.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		this.getSettings().setRenderPriority(RenderPriority.HIGH);
		//TODO
		//this.getSettings().set
		//this.getSettings().setBlockNetworkImage(true);
		//this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		//1 this.getSettings().setTextZoom(100);

		//添加webview重定向和加载的控制函数
		this.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				//reload回调
				if(url.contains("esp")){
					Toast.makeText(espContext, "默认Toast样式",
							Toast.LENGTH_SHORT).show();

					WebViewUtil.openEspUrl(url);
				}else{
					ESPWebView.this.loadUrl(url);
				}
				//////////////loadInterface.Reload(url);
				//progressBar = ProgressDialog.show(espContext, "MaxPowerSoft Example", "Loading...");
				return true;
			}
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {

				super.onPageStarted(view, url, favicon);
				//load回调
				LoadingDataUtilBlack.show(espContext);
				//LoadingDataUtil.show();
				// progressBar = ProgressDialog.show(espContext, "MaxPowerSoft Example", "Loading...");
				////////// loadInterface.load(url);
				//ESPWebView.this.loadUrl(url);
			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				if (progressBar.isShowing()) {
					progressBar.dismiss();
				}
				//LoadingDataUtil.dismiss();
				LoadingDataUtilBlack.dismiss();
			}
			@Override
			public void onReceivedError(WebView view, int errorCode,
										String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				LoadingDataUtilBlack.dismiss();

			}


			public void onReceivedSslError(WebView view, SslErrorHandler handler,
										   SslError error) {
				// handler.cancel(); 默认的处理方式，WebView变成空白页
				handler.proceed();// 接受证书
				LoadingDataUtilBlack.dismiss();

				// handleMessage(Message msg); 其他处理k
			}
		});
	}

	// js android 交互标示的方法（无参数）
	public void jsToAndroid() {
		// jsToAndroidInterface.jsToAndroid();
	}

	// js android 交互标示的方法（有参数）
	public void jsToAndroid(String xx) {
		System.out.println("...................jsToAndroid" + xx);
		// FIXME 有时候不显示“正在加载数据”
		if (xx.equals("start")) {
			Log.i("test-form-time", "startLoadForm -----> formCreated 耗时: " + (System.currentTimeMillis() - Constant.currentTimeMillis) + " 毫秒");
			Constant.currentTimeMillis = System.currentTimeMillis();
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					LoadingDataUtilBlack.show(espContext, "正在加载数据");
				}
			}, 50);
			
		} else if (xx.equals("stop")) {
			LoadingDataUtilBlack.dismiss();

			// LoadingDataUtilBlack.show("正在加载数据");
		} else if (xx.equals("formcreate")) {
			/*System.out.println("...................formcreate");
			Intent mIntent = new Intent("formcreate");
			mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");

			// 发送广播
			espContext.sendBroadcast(mIntent);*/
			Log.i("TimeCheck","加载所有js完成————————"+new Date(System.currentTimeMillis()));
			isinitover  = true;
			jsToandroidCallBack.html5initover();
			

		} else if (xx.equals("dataLoaded")) {
			Log.i("test-form-time", "formCreated  -----> dataLoaded 耗时: " + (System.currentTimeMillis() - Constant.currentTimeMillis) + " 毫秒");
			Constant.currentTimeMillis = System.currentTimeMillis();
			Log.i("test-form-time", "-----------> end:" + new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()) + "-----------");
			Intent mIntent = new Intent(MyStaticWebView.getFormtitle());
			mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
			mIntent.putExtra("type", xx);
			// 发送广播
			espContext.sendBroadcast(mIntent);
			// LoadingDataUtil.dismiss();
		} else if (xx.contains("AndroidScrollArea")) {
			int i = xx.indexOf("-");
			canScrollscaleArray = xx.substring(i + 1, xx.length());

			// LoadingDataUtil.dismiss();
		}

		// jsToAndroidInterface.jsToAndroid(xx);
	}

	// load回调
	public interface LoadInterface {
		public void load(String url);

		public void Reload(String url);

	}
	public String getValueFromNative(String param){
		String value = EnvironmentVariable.getProperty(param,"");
		return  value;
	}
	// js android 交互回调
	public interface JsToAndroidInterface {
		public void jsToAndroid();

		public void jsToAndroid(String xx);
	}

	public void setJsToAndroidInterface(
			JsToAndroidInterface jsToandroidInterface) {
		this.jsToAndroidInterface = jsToandroidInterface;
	}

	public void setLoadInterface(LoadInterface loadinterface) {
		this.loadInterface = loadinterface;
	}


	boolean mIgnoreTouchCancel;

	public void ignoreTouchCancel(boolean val) {
		mIgnoreTouchCancel = val;
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			onScrollChanged(getScrollX(), getScrollY(), getScrollX(),
					getScrollY());
		}
		return super.onTouchEvent(ev);
	}

	/*
	 * (non-Javadoc)目前此方法无效
	 * @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
	 */
/*	@Override
	public boolean onInterceptTouchEvent(MotionEvent arg0) {
		float contentHeight = this.getContentHeight() * this.getScale();
		float clickHeight = arg0.getY() + this.getScrollY();
		float bili = clickHeight / contentHeight;
		String bilistring = canScrollscaleArray;
		if (bilistring != null) {
			String[] biliarray = bilistring.split(",");

			for (int i = 0; i < biliarray.length; i++) {
				Float listbilicontent = Float.parseFloat(biliarray[i]);
				Float listbilicontentnext = Float.parseFloat(biliarray[i + 1]);
				System.out
						.println("iscanscroll==="
								+ (bili < listbilicontentnext && bili > listbilicontent)
								+ "    bili====" + clickHeight / contentHeight
								+ "   clickHeight ===" + clickHeight
								+ "   contentHeight==" + contentHeight
								+ "  点击时的位置" + arg0.getY() + "  滚动的距离"
								+ this.getScrollY() + " listbilicontent==="
								+ listbilicontent + "  listbilicontentnext "
								+ listbilicontentnext);
				if (bili < listbilicontentnext && bili > listbilicontent) {
					// setCanScroll(false);
					this.getParent().requestDisallowInterceptTouchEvent(true);
					break;
				} else {
					// setCanScroll(true);
					// this.requestDisallowInterceptTouchEvent(true);
					this.getParent().requestDisallowInterceptTouchEvent(false);
				}
				i++;
			}
		}
		return super.onInterceptTouchEvent(arg0);
	}*/
	public interface JsToandroidCallBack{
		public void html5initover();
		
	}
}
